import { useState, useEffect, useRef } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'
import { ScrollArea } from '@/components/ui/scroll-area'
import { Send, Image, Mic, Play, Pause } from 'lucide-react'

const API_BASE_URL = 'http://localhost:5000/api'

export default function ChatView({ circle, user }) {
  const [messages, setMessages] = useState([])
  const [newMessage, setNewMessage] = useState('')
  const [loading, setLoading] = useState(false)
  const [isRecording, setIsRecording] = useState(false)
  const [playingVoice, setPlayingVoice] = useState(null)
  const scrollAreaRef = useRef(null)
  const messagesEndRef = useRef(null)

  useEffect(() => {
    fetchMessages()
    
    // 每5秒刷新一次消息
    const interval = setInterval(fetchRecentMessages, 5000)
    return () => clearInterval(interval)
  }, [circle.id])

  useEffect(() => {
    // 滚动到底部
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
  }, [messages])

  const fetchMessages = async () => {
    try {
      const response = await fetch(
        `${API_BASE_URL}/messages/circles/${circle.id}/messages?user_id=${user.id}&per_page=50`
      )
      const data = await response.json()
      
      if (response.ok) {
        setMessages(data.messages.reverse()) // 反转顺序，最新消息在底部
      }
    } catch (err) {
      console.error('获取消息失败:', err)
    }
  }

  const fetchRecentMessages = async () => {
    if (messages.length === 0) return
    
    const lastMessage = messages[messages.length - 1]
    try {
      const response = await fetch(
        `${API_BASE_URL}/messages/circles/${circle.id}/messages/recent?user_id=${user.id}&since=${lastMessage.timestamp}&limit=10`
      )
      const data = await response.json()
      
      if (response.ok && data.length > 0) {
        setMessages(prev => [...prev, ...data.reverse()])
      }
    } catch (err) {
      console.error('获取最新消息失败:', err)
    }
  }

  const sendMessage = async (messageType, content, fileUrl = null, duration = null) => {
    try {
      const response = await fetch(`${API_BASE_URL}/messages/messages`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          circle_id: circle.id,
          sender_id: user.id,
          message_type: messageType,
          content,
          file_url: fileUrl,
          duration,
        }),
      })

      const data = await response.json()
      
      if (response.ok) {
        setMessages(prev => [...prev, data])
        setNewMessage('')
      }
    } catch (err) {
      console.error('发送消息失败:', err)
    }
  }

  const handleSendText = () => {
    if (!newMessage.trim()) return
    sendMessage('text', newMessage.trim())
  }

  const handleKeyPress = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault()
      handleSendText()
    }
  }

  const handleImageUpload = () => {
    // 模拟图片上传
    const mockImageUrl = 'https://picsum.photos/300/200'
    sendMessage('image', '', mockImageUrl)
  }

  const handleVoiceRecord = () => {
    if (isRecording) {
      // 停止录音
      setIsRecording(false)
      // 模拟语音消息
      const mockVoiceUrl = 'https://example.com/voice.mp3'
      sendMessage('voice', '', mockVoiceUrl, 15)
    } else {
      // 开始录音
      setIsRecording(true)
      // 模拟录音3秒后自动停止
      setTimeout(() => {
        setIsRecording(false)
        const mockVoiceUrl = 'https://example.com/voice.mp3'
        sendMessage('voice', '', mockVoiceUrl, 3)
      }, 3000)
    }
  }

  const handlePlayVoice = (messageId) => {
    if (playingVoice === messageId) {
      setPlayingVoice(null)
    } else {
      setPlayingVoice(messageId)
      // 模拟播放完成
      setTimeout(() => setPlayingVoice(null), 3000)
    }
  }

  const formatTime = (timestamp) => {
    const date = new Date(timestamp)
    return date.toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit' 
    })
  }

  const renderMessage = (message) => {
    const isOwn = message.sender_id === user.id
    
    return (
      <div
        key={message.id}
        className={`flex ${isOwn ? 'justify-end' : 'justify-start'} mb-4`}
      >
        {!isOwn && (
          <Avatar className="w-8 h-8 mr-2">
            <AvatarImage src={message.sender?.avatar_url} />
            <AvatarFallback className="bg-gray-300 text-gray-600 text-xs">
              {message.sender?.nickname?.charAt(0) || '用'}
            </AvatarFallback>
          </Avatar>
        )}
        
        <div className={`max-w-[70%] ${isOwn ? 'order-1' : ''}`}>
          {!isOwn && (
            <div className="text-xs text-gray-500 mb-1">
              {message.sender?.nickname}
            </div>
          )}
          
          <div
            className={`rounded-lg px-3 py-2 ${
              isOwn
                ? 'bg-walker-orange text-white'
                : 'bg-white border border-gray-200'
            }`}
          >
            {message.message_type === 'text' && (
              <p className="text-sm">{message.content}</p>
            )}
            
            {message.message_type === 'image' && (
              <div className="w-48 h-32 bg-gray-100 rounded flex items-center justify-center">
                <Image className="w-8 h-8 text-gray-400" />
                <span className="ml-2 text-sm text-gray-500">图片消息</span>
              </div>
            )}
            
            {message.message_type === 'voice' && (
              <div className="flex items-center space-x-2 min-w-[120px]">
                <Button
                  size="sm"
                  variant="ghost"
                  onClick={() => handlePlayVoice(message.id)}
                  className={`p-1 ${isOwn ? 'text-white hover:bg-white/20' : ''}`}
                >
                  {playingVoice === message.id ? (
                    <Pause className="w-4 h-4" />
                  ) : (
                    <Play className="w-4 h-4" />
                  )}
                </Button>
                <div className="flex-1 flex items-center space-x-1">
                  <div className="flex space-x-1">
                    {[...Array(5)].map((_, i) => (
                      <div
                        key={i}
                        className={`w-1 bg-current rounded-full ${
                          playingVoice === message.id ? 'animate-pulse' : ''
                        }`}
                        style={{ height: `${8 + Math.random() * 8}px` }}
                      />
                    ))}
                  </div>
                  <span className="text-xs">{message.duration}"</span>
                </div>
              </div>
            )}
          </div>
          
          <div className={`text-xs text-gray-400 mt-1 ${isOwn ? 'text-right' : ''}`}>
            {formatTime(message.timestamp)}
          </div>
        </div>
        
        {isOwn && (
          <Avatar className="w-8 h-8 ml-2">
            <AvatarImage src={user.avatar_url} />
            <AvatarFallback className="bg-walker-orange text-white text-xs">
              {user.nickname?.charAt(0) || '我'}
            </AvatarFallback>
          </Avatar>
        )}
      </div>
    )
  }

  return (
    <div className="h-full flex flex-col">
      {/* 消息列表 */}
      <ScrollArea className="flex-1 p-4" ref={scrollAreaRef}>
        <div className="space-y-2">
          {messages.map(renderMessage)}
          <div ref={messagesEndRef} />
        </div>
      </ScrollArea>

      {/* 录音状态 */}
      {isRecording && (
        <div className="bg-red-50 border-t border-red-200 p-3">
          <div className="flex items-center justify-center space-x-2 text-red-600">
            <div className="w-2 h-2 bg-red-500 rounded-full animate-pulse"></div>
            <span className="text-sm">正在录音...</span>
          </div>
        </div>
      )}

      {/* 输入区域 */}
      <div className="bg-white border-t p-3">
        <div className="flex items-center space-x-2">
          <Button
            size="sm"
            variant="outline"
            onClick={handleImageUpload}
          >
            <Image className="w-4 h-4" />
          </Button>
          
          <div className="flex-1">
            <Input
              placeholder="输入消息..."
              value={newMessage}
              onChange={(e) => setNewMessage(e.target.value)}
              onKeyPress={handleKeyPress}
            />
          </div>
          
          <Button
            size="sm"
            variant="outline"
            onClick={handleVoiceRecord}
            className={isRecording ? 'bg-red-100 border-red-300' : ''}
          >
            <Mic className="w-4 h-4" />
          </Button>
          
          <Button
            size="sm"
            onClick={handleSendText}
            disabled={!newMessage.trim()}
            className="bg-walker-orange hover:bg-walker-orange/90"
          >
            <Send className="w-4 h-4" />
          </Button>
        </div>
      </div>
    </div>
  )
}

